package com.aw.guiguzi.widgets

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.RadioButton
import android.widget.Spinner
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwBaseConstant
import com.aw.baselib.util.AwConvertUtil
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwDateUtil
import com.aw.baselib.util.AwPopupwindowUtil
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwToastUtil
import com.aw.guiguzi.R
import com.aw.guiguzi.adapter.NumSingleCheckRateAnalysisAdapter
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.bean.NumItemBean
import com.aw.guiguzi.enums.NumBettingEnums
import com.aw.guiguzi.util.AppCacheUtil
import java.util.Arrays
import java.util.Date

class NumSingleCheckRateAnalysisPopupWindow(private val mActivity: Activity) : PopupWindow() {
    private val contentView: View
    private val mAdapter: NumSingleCheckRateAnalysisAdapter
    private val rcv_data: RecyclerView
    private var mList: List<NumItemBean?> = ArrayList()
    private val mResultToShowList: MutableList<String> = ArrayList()
    private var mCurrentNumItembean: NumItemBean? = null

    init {
        mList = MyApp.mAllNumImitateList
        contentView =
            View.inflate(mActivity, R.layout.view_popupwindow_num_single_check_rate_analysis, null)
        rcv_data = contentView.findViewById(R.id.rcv_dataResult)
        val tv_config = contentView.findViewById<Spinner>(R.id.tv_config)
        val iv_close = contentView.findViewById<ImageView>(R.id.iv_close)
        val tv_toCal = contentView.findViewById<TextView>(R.id.tv_toCal)
        val tv_customConfig = contentView.findViewById<TextView>(R.id.tv_customConfig)
        val rBtn_calLength7 = contentView.findViewById<RadioButton>(R.id.rBtn_calLength7)
        val rBtn_calLength6 = contentView.findViewById<RadioButton>(R.id.rBtn_calLength6)
        val rBtn_calLength5 = contentView.findViewById<RadioButton>(R.id.rBtn_calLength5)
        val rBtn_calLength4 = contentView.findViewById<RadioButton>(R.id.rBtn_calLength4)
        val rBtn_calLength3 = contentView.findViewById<RadioButton>(R.id.rBtn_calLength3)
        val et_winCount = contentView.findViewById<EditText>(R.id.et_winCount)
        val et_totalEvents = contentView.findViewById<EditText>(R.id.et_totalEvents)
        mAdapter = NumSingleCheckRateAnalysisAdapter()
        AwRecyclerViewUtil.setRecyclerViewLinearlayout(mActivity, rcv_data, mAdapter, false)
        mAdapter.addAllData(mResultToShowList)
        tv_toCal.setOnClickListener { v: View? ->
            var bettingNums = 5
            if (rBtn_calLength7.isChecked) {
                bettingNums = 7
            } else if (rBtn_calLength6.isChecked) {
                bettingNums = 6
            } else if (rBtn_calLength5.isChecked) {
                bettingNums = 5
            } else if (rBtn_calLength4.isChecked) {
                bettingNums = 4
            } else if (rBtn_calLength3.isChecked) {
                bettingNums = 3
            }
            toCalResult(bettingNums, et_winCount.text.toString(), et_totalEvents.text.toString())
        }
        tv_customConfig.text =
            "宝石" + mList[0]?.getGemstoneCount() + "，银" + mList[0]?.getSilverCount() + "，皮" + mList[0]?.getSkinCount()
        val defalutIndex = defaultConfigCountIndex
        tv_customConfig.visibility = if (defalutIndex == 0) View.VISIBLE else View.GONE
        tv_config.setSelection(defalutIndex)
        tv_config.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                tv_customConfig.visibility = if (position == 0) View.VISIBLE else View.GONE
                setListItemCount(parent.selectedItem as String)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        iv_close.setOnClickListener { v: View? -> dismiss() }
        contentView.findViewById<View>(R.id.iv_delConfigNums)
            .setOnClickListener { v: View? -> clearAllSelect() }
        setContentView(contentView)
        this.width = ViewGroup.LayoutParams.MATCH_PARENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.animationStyle = com.aw.baselib.R.style.sytle_anim_pop_in_out
        this.isFocusable = true
        this.isTouchable = true
        this.isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        this.update()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.overlapAnchor = true
        }
        setOnDismissListener {
            val lp = mActivity.window.attributes
            lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_NORMAL
            mActivity.window.attributes = lp
        }
    }

    private fun clearAllSelect() {
        for (itemBean in mList) {
            itemBean!!.isChecked = false
        }
        mAdapter.notifyDataSetChanged()
    }

    private val defaultConfigCountIndex: Int
        private get() {
            val list = Arrays.asList(*mActivity.resources.getStringArray(R.array.config_count))
            return list.indexOf(AppCacheUtil.getBettingConfigCount())
        }

    private fun setListItemCount(name: String) {
        if (AwDataUtil.isEmpty(mList)) {
            return
        }
        AppCacheUtil.setBettingConfigCount(name)
        for (itemBean in mList) {
            if (name == NumBettingEnums.MODE_1_1_10.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(10)
            } else if (name == NumBettingEnums.MODE_1_1_20.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(20)
            } else if (name == NumBettingEnums.MODE_1_1_40.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_2_2_20.name) {
                itemBean!!.setSilverCount(2)
                itemBean.setSkinCount(2)
                itemBean.setGemstoneCount(20)
            } else if (name == NumBettingEnums.MODE_2_2_40.name) {
                itemBean!!.setSilverCount(2)
                itemBean.setSkinCount(2)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_3_3_30.name) {
                itemBean!!.setSilverCount(3)
                itemBean.setSkinCount(3)
                itemBean.setGemstoneCount(30)
            } else if (name == NumBettingEnums.MODE_4_4_40.name) {
                itemBean!!.setSilverCount(4)
                itemBean.setSkinCount(4)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_5_5_50.name) {
                itemBean!!.setSilverCount(5)
                itemBean.setSkinCount(5)
                itemBean.setGemstoneCount(50)
            } else if (name == NumBettingEnums.MODE_5_5_100.name) {
                itemBean!!.setSilverCount(5)
                itemBean.setSkinCount(5)
                itemBean.setGemstoneCount(100)
            } else if (name == NumBettingEnums.MODE_10_10_100.name) {
                itemBean!!.setSilverCount(10)
                itemBean.setSkinCount(10)
                itemBean.setGemstoneCount(100)
            } else if (name == NumBettingEnums.MODE_10_10_200.name) {
                itemBean!!.setSilverCount(10)
                itemBean.setSkinCount(10)
                itemBean.setGemstoneCount(200)
            } else {
                val bettingCustomArrays = AppCacheUtil.getBettingCustom().split("/".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                itemBean!!.setSilverCount(AwDataUtil.getIntValue(bettingCustomArrays[0]))
                itemBean.setSkinCount(AwDataUtil.getIntValue(bettingCustomArrays[1]))
                itemBean.setGemstoneCount(AwDataUtil.getIntValue(bettingCustomArrays[2]))
            }
            mCurrentNumItembean = itemBean
        }
    }

    private fun toCalResult(bettingNums: Int, winCount: String, totalEvents: String) {
        if (AwDataUtil.isEmpty(winCount) || AwDataUtil.isEmpty(totalEvents)) {
            AwToastUtil.show("请输入获胜次数及总场次")
            return
        }
        if (mCurrentNumItembean == null) {
            AwToastUtil.show("请选择下注配置")
            return
        }
        //出数结果 - 总成本 = 最后盈亏
        val rateNum = java.lang.Double.valueOf(
            AwConvertUtil.div(
                java.lang.Double.valueOf(winCount),
                java.lang.Double.valueOf(totalEvents)
            )
        )
        val totalEventsNum = totalEvents.toInt().toDouble()
        val silverCount = mCurrentNumItembean!!.getSilverCount()
        val skinCount = mCurrentNumItembean!!.getSkinCount()
        val gemstoneCount = mCurrentNumItembean!!.getGemstoneCount()

        //总成本
        val silverCountTotal = (silverCount * totalEventsNum * bettingNums).toInt()
        val skinCountTotal = (skinCount * totalEventsNum * bettingNums).toInt()
        val gemstoneCountTotal = (gemstoneCount * totalEventsNum * bettingNums).toInt()

        //总共赢的
        val silverCountTotalWin = (silverCount * totalEventsNum * rateNum * 10).toInt()
        val skinCountTotalWin = (skinCount * totalEventsNum * rateNum * 10).toInt()
        val gemstoneCountTotalWin = (gemstoneCount * totalEventsNum * rateNum * 10).toInt()
        val silverCountTotalDiff = silverCountTotalWin - silverCountTotal
        val skinCountTotalDiff = skinCountTotalWin - skinCountTotal
        val gemstoneCountTotalDiff = gemstoneCountTotalWin - gemstoneCountTotal
        val dateStr = AwDateUtil.formatDate(Date(System.currentTimeMillis()), "HH:mm:ss")
        val result = "№.【" + dateStr + "】 " + "\n\n" +
                "1️⃣【单数投注】 银：" + silverCount + " ，皮：" + skinCount + " ，宝石：" + gemstoneCount + "，数字数量：" + bettingNums + "个\n" +
                "2️⃣【场次】 获胜次数：" + winCount + " ，总次数：" + totalEvents + "场 ，胜率：" + rateNum * 100 + "%" + " \n" +
                "3️⃣【总成本】 银：" + silverCountTotal + " ，皮：" + skinCountTotal + " ，宝石：" + gemstoneCountTotal + " \n" +
                "4️⃣【总收入】 银：" + silverCountTotalWin + " ，皮：" + skinCountTotalWin + " ，宝石：" + gemstoneCountTotalWin + " \n" +
                "5️⃣【总利润】 银：" + silverCountTotalDiff + " ，皮：" + skinCountTotalDiff + " ，宝石：" + gemstoneCountTotalDiff + " \n"
        //        mResultToShowList.add(result);
        mResultToShowList.add(0, result)
        mAdapter.addAllData(mResultToShowList)
        rcv_data.scrollToPosition(0)
        //        rcv_data.scrollToPosition(mResultToShowList.size() - 1);
    }

    /**
     * 展示窗口
     */
    fun show(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        this.showAsDropDown(parent, 0, 0)
    }

    fun showAsLocation(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationNoAlpha(parent: View?) {
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationBottom(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        showAtLocation(parent, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }

    /**
     * calendar菜单选择监听接口
     */
    interface OnResultCallback {
        fun onResult(list: List<NumItemBean?>?)
    }
}